<template>
  <view class="bg-gray-50 w-[750rpx] pb-[150rpx] box-border bgs">
    <!-- 顶部导航 -->
    <PageHeader title="发布任务" :showBack="true" />
    <!-- <view class="bg-gradient-to-r from-blue-600 to-blue-800 text-white p-[30rpx] sticky top-0 z-100 flex justify-between items-center shadow-lg">
      <IconFont name="arrow-left" class="text-[40rpx] cursor-pointer" @click="handleBack" />
      <text class="text-[36rpx] font-bold flex-1 text-center">发布任务</text>
      <view></view>
    </view> -->

    <!-- 悬赏类型选择 -->
    <!-- <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border">
      <view class="text-[34rpx] font-bold text-gray-800 mb-[30rpx] flex items-center">
        <text>选择任务类型</text>
      </view>
      
      <view class="grid grid-cols-3 gap-[30rpx] text-[24rpx]">
        <view 
          v-for="(type, index) in bountyTypes" 
          :key="index"
          class="rounded-[20rpx] p-[25rpx] text-center cursor-pointer transition-all border-2"
          :class="selectedType === type.value ? 'bg-blue-50 border-blue-500' : 'bg-gray-50 border-transparent'"
          @tap="selectType(type.value)"
        >
          <text :class="selectedType === type.value ? 'text-blue-600 font-bold block' : 'text-gray-800 font-bold block'">{{ type.name }}</text>
        </view>
      </view>
      <view v-if="selectedType === 'recruit'" class="mt-[40rpx]">
        <text class="text-[28rpx] font-medium mb-[20rpx] block">选择招聘类型</text>
        <view class="flex gap-[20rpx] text-[24rpx]">
          <view 
            v-for="(recruitType, index) in recruitTypes" 
            :key="index"
            class="flex-1 rounded-[20rpx] p-[25rpx] text-center cursor-pointer transition-all border-2"
            :class="selectedRecruitType === recruitType.value ? 'bg-blue-50 border-blue-500' : 'bg-gray-50 border-transparent'"
            @tap="selectRecruitType(recruitType.value)"
          >
            <text :class="selectedRecruitType === recruitType.value ? 'text-blue-600 font-bold block' : 'text-gray-800 font-bold block'">{{ recruitType.name }}</text>
          </view>
        </view>
      </view>
    </view> -->

    <!-- 悬赏表单 -->
    <view
      class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border"
    >
      <view
        class="text-[34rpx] font-bold text-gray-800 mb-[30rpx] flex items-center"
      >
        <!-- <IconFont name="edit" class="text-blue-500 mr-[15rpx]" /> -->
        <text>悬赏任务信息</text>
      </view>

      <nut-form ref="formRef" :model="formData">
        <!-- 任务标题 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
            >任务标题</text
          >
          <input
            v-model="formData.title"
            type="text"
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border"
            placeholder="请输入任务标题（50字以内）"
          />
        </view>

        <!-- 任务分类 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
            >任务分类</text
          >
          <view
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border"
            @click="showCategoryPicker = true"
          >
            {{ categoryText || "请选择任务分类" }}
          </view>
          <nut-popup
            v-model:visible="showCategoryPicker"
            position="bottom"
            round
          >
            <nut-picker
              v-model="categoryValue"
              :columns="categoryOptions"
              title="请选择任务分类"
              @confirm="onCategoryConfirm"
              @cancel="showCategoryPicker = false"
            />
          </nut-popup>
        </view>

        <!-- 任务标签 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
            >任务标签</text
          >

          <!-- 添加技能 -->
          <view class="flex mb-[24rpx]">
            <nut-input
              v-model="newSkill"
              placeholder="输入标签后点击添加"
              class="flex-1 rounded-l-[15rpx] border-2 border-gray-200 p-[20rpx] text-[28rpx] bg-gray-50"
              @keypress="onSkillKeyPress"
            />
            <nut-button
              type="primary"
              class="rounded-r-[15rpx] text-[28rpx] bg-blue-600 border-none h-[84rpx] px-[30rpx]"
              @click="addSkill"
            >
              添加
            </nut-button>
          </view>

          <!-- 显示标签 -->
          <view class="flex flex-wrap gap-[16rpx]">
            <view
              v-for="(tag, index) in tags"
              :key="index"
              class="flex items-center bg-blue-50 text-blue-600 px-[20rpx] py-[12rpx] rounded-[30rpx] text-[26rpx] border border-blue-100"
            >
              <text>{{ tag }}</text>
              <IconFont
                name="close"
                size="10"
                class="ml-[12rpx] text-[24rpx] text-blue-400 cursor-pointer"
                @click="removeSkill(index)"
              />
            </view>
          </view>
        </view>

        <!-- 任务描述 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
            >任务描述</text
          >
          <nut-textarea
            v-model="formData.description"
            style="height: 100%"
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 min-h-[120rpx] max-h-[400rpx] box-border resize-none"
            placeholder="请详细描述任务要求、完成标准、注意事项等"
          />
        </view>

        <!-- 截止日期 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
            >截止日期</text
          >
          <view
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border"
            @click="showDatePicker = true"
          >
            {{
              formData.deadline
                ? formatDate(formData.deadline)
                : "请选择任务截止日期"
            }}
          </view>
          <nut-popup v-model:visible="showDatePicker" position="bottom" round>
            <nut-date-picker
              v-model="dateValue"
              title="请选择任务截止日期"
              type="date"
              @confirm="onDateConfirm"
              @cancel="showDatePicker = false"
            />
          </nut-popup>
        </view>

        <!-- 任务地点 -->
        <!-- <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800"
            >任务地点</text
          >
          <view
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border flex items-center justify-between cursor-pointer"
            @click="showMapPicker = true"
          >
            <text
              :class="formData.location ? 'text-gray-800' : 'text-gray-400'"
            >
              {{ formData.location || "点击选择任务地点" }}
            </text>
            <IconFont name="location" class="text-[32rpx] text-blue-500" />
          </view>
        </view> -->
      </nut-form>
    </view>

    <!-- 阶段悬赏设置 -->
    <view
      class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border"
    >
      <view class="flex justify-between items-center mb-[30rpx]">
        <text class="text-[32rpx] font-bold text-gray-800">阶段任务设置</text>
        <!-- <nut-button 
      type="primary" 
      size="small"
      class="px-[30rpx] py-[15rpx] text-[26rpx]"
      @click="addStage"
    >
      <IconFont name="plus" class="mr-[10rpx]" />
      添加阶段
    </nut-button> -->
      </view>

      <view
        v-for="(stage, index) in stages"
        :key="index"
        class="bg-gray-50 rounded-[20rpx] p-[30rpx] mb-[30rpx] relative"
      >
        <!-- 删除按钮 -->
        <view class="absolute top-[20rpx] right-[20rpx] z-10">
          <IconFont
            v-if="stages.length > 1"
            name="close"
            color="#000"
            size="16"
            @click="removeStage(index)"
          />
        </view>

        <view class="flex justify-between items-center mb-[20rpx]">
          <text class="text-[30rpx] font-bold text-gray-800"
            >第{{ index + 1 }}阶段</text
          >
        </view>

        <view class="flex items-center mb-[20rpx]">
          <text class="text-[28rpx] text-gray-600 mr-[20rpx] w-[150rpx]"
            >阶段金额</text
          >
          <input
            v-model="stage.price"
            type="number"
            class="flex-1 p-[20rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-white box-border"
            placeholder="0"
            min="0"
            @input="calculateTotal"
          />
        </view>

        <!-- 新增的阶段周期部分 -->
        <view class="flex items-center mb-[20rpx]">
          <text class="text-[28rpx] text-gray-600 mr-[20rpx] w-[150rpx]"
            >阶段周期</text
          >
          <input
            v-model="stage.cycle"
            type="number"
            class="flex-1 p-[20rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-white box-border"
            placeholder="0"
            min="0"
          />
          <text
            class="text-[28rpx] text-gray-600 ml-[20rpx] w-[80rpx] text-center"
            >天</text
          >
        </view>

        <view class="mt-[20rpx]">
          <text class="text-[28rpx] font-medium mb-[15rpx] block"
            >阶段描述</text
          >
          <input
            v-model="stage.describe"
            type="text"
            class="w-full p-[20rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-white box-border"
            placeholder="请描述本阶段任务要求"
          />
        </view>

        <!-- 添加阶段按钮 -->
        <view class="text-center mt-[20rpx] relative">
          <view
            class="bg-white flex items-center justify-center bg-gray-100 active:bg-gray-200 border-1 border-solid border-gray-500 px-[20rpx] py-2 relative z-2 text-gray-500 text-[26rpx] cursor-pointer"
            @click="addStageAfter(index)"
          >
            <IconFont name="plus" class="text-[32rpx]" />添加新阶段
          </view>
        </view>
      </view>
    </view>

    <!-- 金额总计 -->
    <view
      class="bg-gradient-to-r from-blue-600 to-blue-800 text-white rounded-[25rpx] p-[30rpx] m-[30rpx] flex justify-between items-center box-border"
    >
      <text class="text-[32rpx] font-bold">任务总金额</text>
      <text class="text-[48rpx] font-bold">¥ {{ totalAmount }}</text>
    </view>

    <!-- 服务方选择 -->
    <view
      class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg mb-[30rpx] box-border"
    >
      <view class="text-[32rpx] font-bold mb-[30rpx] flex items-center">
        <!-- <IconFont name="users" class="text-[#2196F3] mr-[15rpx]" /> -->
        <text>服务方选择</text>
      </view>
      <!-- 单选框组 -->
      <nut-radio-group
        v-model="providerType"
        direction="horizontal"
        class="gap-x-[40rpx] mb-[30rpx] flex items-center"
      >
        <nut-radio
          :label="'all'"
          class="text-[28rpx] !text-[#2196F3] flex items-center"
          >不限</nut-radio
        >
        <nut-radio
          :label="'person'"
          class="text-[28rpx] !text-[#2196F3] flex items-center"
          >个人从业者</nut-radio
        >
        <nut-radio
          :label="'company'"
          class="text-[28rpx] !text-[#2196F3] flex items-center"
          >服务商</nut-radio
        >
      </nut-radio-group>

      <!-- 服务商列表 -->
      <view v-if="providerType === 'all' || providerType === 'company'">
        <view class="text-[28rpx] font-medium my-[20rpx]">可选服务商</view>
        <view class="grid grid-cols-2 gap-[20rpx]">
          <view
            v-for="company in companyList"
            :key="company.id"
            class="flex items-center bg-gray-50 rounded-[15rpx] p-[20rpx] border-2 transition-all border-transparent hover:border-[#2196F3]"
          >
            <nut-checkbox
              :model-value="selectedCompanies.includes(company.id)"
              @update:model-value="(val) => handleCompanyCheck(val, company.id)"
              class="mr-[4rpx] !text-[#2196F3]"
            />
            <!-- <IconFont name="building" class="text-[36rpx] text-[#2196F3] mr-[10rpx]" /> -->
            <view class="flex-1 min-w-0">
              <text
                class="text-[28rpx] font-bold text-gray-800 truncate block"
                >{{ company.name }}</text
              >
              <text class="block text-[24rpx] text-gray-500 truncate">{{
                company.desc
              }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 个人从业者列表 -->
      <view v-if="providerType === 'all' || providerType === 'person'">
        <view class="text-[28rpx] font-medium my-[20rpx]">可选个人从业者</view>
        <view class="grid grid-cols-2 gap-[20rpx] mb-[20rpx]">
          <view
            v-for="person in personList"
            :key="person.id"
            class="flex items-center bg-gray-50 rounded-[15rpx] p-[20rpx] border-2 transition-all border-transparent hover:border-[#2196F3]"
          >
            <nut-checkbox
              :model-value="selectedPersons.includes(person.id)"
              @update:model-value="(val) => handlePersonCheck(val, person.id)"
              class="mr-[15rpx] !text-[#2196F3]"
            />
            <IconFont
              name="user"
              class="text-[36rpx] text-[#2196F3] mr-[10rpx]"
            />
            <view class="flex-1 min-w-0">
              <text
                class="text-[28rpx] font-bold text-gray-800 truncate block"
                >{{ person.name }}</text
              >
              <text class="block text-[24rpx] text-gray-500 truncate">{{
                person.desc
              }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 区域选择 -->
    <view class="bg-white p-[40rpx] m-[30rpx] box-border">
      <view class="text-[32rpx] font-bold mb-[36rpx]">区域选择</view>
      <nut-radio-group
        v-model="regionLevel"
        direction="vertical"
        class="w-full"
      >
        <view
          v-for="item in regionOptions"
          :key="item.value"
          class="flex items-center py-[20rpx] border-b border-gray-200 last:border-b-0 cursor-pointer select-none text-[28rpx] transition-all"
        >
          <nut-radio
            :label="item.value"
            class="mr-[24rpx] text-blue-600 flex items-center"
          />
          <text
            :class="
              regionLevel === item.value
                ? 'text-blue-600 font-bold'
                : 'text-gray-500'
            "
            >{{ item.label }}</text
          >
          <text class="ml-1 text-gray-400">（信息费{{ item.fee }}元）</text>
        </view>
      </nut-radio-group>
      <view class="text-[28rpx] mt-[24rpx]">
        当前选择：{{ getRegionText(regionLevel as string) }}，信息费¥{{
          regionFeeMap[regionLevel]
        }}
      </view>
    </view>

    <!-- 支付按钮 -->
    <view
      class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg text-center box-border"
    >
      <nut-button
        type="primary"
        size="large"
        class="w-full text-[36rpx] font-bold bg-gradient-to-r from-orange-400 to-red-500 h-[96rpx]"
        @click="handlePayment"
      >
        <IconFont name="lock" class="mr-[15rpx]" />
        支付任务金额并发布
      </nut-button>
      <text class="text-[26rpx] text-gray-600 mt-[30rpx] block">
        支付后金额将托管在平台，任务完成后支付给执行方
      </text>
    </view>

    <!-- 地图选择器 -->
    <MapPicker
      v-model="showMapPicker"
      :default-location="defaultMapLocation"
      @confirm="handleLocationConfirm"
    />

    <!-- 流程说明 -->
    <view
      class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border"
    >
      <text
        class="text-[32rpx] font-bold text-gray-800 mb-[30rpx] text-center block"
        >任务流程说明</text
      >

      <view class="flex flex-col gap-[30rpx]">
        <view
          v-for="(step, index) in processSteps"
          :key="index"
          class="flex items-start"
        >
          <view
            class="w-[50rpx] h-[50rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[30rpx] font-bold mr-[20rpx] flex-shrink-0"
          >
            {{ index + 1 }}
          </view>
          <view class="flex-1">
            <text
              class="text-[30rpx] font-bold text-gray-800 mb-[10rpx] block"
              >{{ step.title }}</text
            >
            <text class="text-[26rpx] text-gray-600 leading-[1.5]">{{
              step.desc
            }}</text>
          </view>
        </view>
      </view>

      <view
        class="bg-yellow-50 border-l-5 border-yellow-400 p-[20rpx] rounded-[10rpx] mt-[20rpx] text-[26rpx] text-gray-600"
      >
        <IconFont
          name="exclamation-circle"
          class="text-yellow-400 mr-[10rpx]"
        />
        如出现纠纷：任何一方可点击"我有异议"，平台将冻结该笔交易金额，双方协商一致后解锁交易并按流程核销。
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
// import { Radio as nutRadio, RadioGroup as nutRadioGroup, Checkbox as nutCheckbox } from '@nutui/nutui-taro'
import PageHeader from "@/components/PageHeader.vue";
import MapPicker from "@/components/MapPicker.vue";
import { post } from "@/utils/request";
import { getTaskType } from "@/utils/comm";

// 定义接口
interface CategoryColumn {
  update_time: null | number;
  create_time: number;
  name: string;
  id: number;
  pic: string;
}

interface CategoryItem {
  columns: CategoryColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

export interface taskRequest {
  city?: string;
  // 周期
  cycle?: string;
  // 截止日期
  deadline?: string;
  // 描述
  describe?: string;
  // 行业ID
  industryId?: string;
  // 纬度
  latitude?: string;
  // 经度
  longitude?: string;
  range?: string;
  // 是否上热门 0 不  1 上
  recommend?: number;
  // 主任务状态  0 发布中 1 进行中 2 待确认完成 3 确认没完成 4 确认已完成
  status?: number;
  taskStages?: TaskStageVo[];
  // 类型
  taskType?: number;
  // 标题
  title?: string;
  // 标签
  tags?: string[];
  // 邀请服务方
  userIds?: number[];
  [property: string]: any;
}

/**
 * 任务阶段
 *
 * TaskStageVo
 */
export interface TaskStageVo {
  // 任务周期(天)
  cycle?: number;
  // 描述
  describe?: number;
  id?: number;
  // 价格
  price?: number;
  // 任务状态  0所有  1 发布中  2 进行中 3 待确认完成 4 确认没完成 5 确认已完成(待评价) 6 已评价
  status?: number;
  // 任务ID
  taskId?: number;
  [property: string]: any;
}

// 悬赏类型
const bountyTypes = ref([
  { name: "日结类", value: "daily", icon: "calendar-day" },
  { name: "悬赏类", value: "bounty", icon: "award" },
  { name: "招聘类", value: "recruit", icon: "briefcase" },
]);

// 招聘类型
const recruitTypes = ref([
  { name: "工厂类", value: "factory", icon: "industry" },
  { name: "特殊类", value: "special", icon: "star" },
]);

// 任务分类选项
const categoryOptions = ref<{ text: string; value: string }>([]);

// 流程步骤
const processSteps = ref([
  { title: "发布任务", desc: "填写任务信息并支付任务金额到平台" },
  { title: "执行方申请", desc: "平台从业者在线申请执行任务" },
  { title: "选择执行方", desc: "您可以选择申请者或邀请特定从业者" },
  { title: "开始执行", desc: "双方同意后正式开始执行任务" },
  { title: "阶段结算", desc: "每个阶段完成后单独结算该阶段金额" },
]);

// 选中状态
const selectedType = ref("daily");
const selectedRecruitType = ref("");

// 标签相关
const tags = ref([]);
const newSkill = ref([]);
function onSkillKeyPress(e: any) {
  if (e.key === "Enter") {
    addSkill();
  }
}
function addSkill() {
  const skill = newSkill.value.trim();
  if (skill && !tags.value.includes(skill)) {
    tags.value.push(skill);
    newSkill.value = "";
  }
}
function removeSkill(index: number) {
  tags.value.splice(index, 1);
}

// 表单数据
// const formData = reactive({
//   title: '',
//   category: '',
//   description: '',
//   deadline: '',
//   location: '',
//   longitude: '',
//   latitude: ''
// })

const formData = reactive<taskRequest>({});
const taskStages = ref<TaskStageVo[]>([]);

// 阶段数据
const stages = ref<TaskStageVo>([
  { price: "", describe: "", cycle: "" },
  { price: "", describe: "", cycle: "" },
  { price: "", describe: "", cycle: "" },
]);

// 计算总金额
const totalAmount = computed(() => {
  return stages.value
    .reduce((total, stage) => {
      return total + (parseFloat(stage.price) || 0);
    }, 0)
    .toFixed(2);
});

// 选择类型
const selectType = (type: string) => {
  selectedType.value = type;
};

// 选择招聘类型
const selectRecruitType = (type: string) => {
  selectedRecruitType.value = type;
};

// 添加阶段
const addStage = () => {
  stages.value.push({ amount: 0, description: "" });
};

// 在指定阶段后添加新阶段
const addStageAfter = (index: number) => {
  stages.value.splice(index + 1, 0, { amount: 0, description: "" });
};

// 删除阶段
const removeStage = (index: number) => {
  if (stages.value.length > 1) {
    stages.value.splice(index, 1);
  } else {
    Taro.showToast({
      title: "至少需要保留一个阶段",
      icon: "none",
    });
  }
};

// 计算总金额
const calculateTotal = () => {
  // 触发计算，computed会自动更新
};

// 返回
const handleBack = () => {
  Taro.navigateBack();
};

/**
 * 服务方类型
 * @type {import('vue').Ref<'all'|'person'|'company'>}
 */
const providerType = ref<"all" | "person" | "company">("all");

/**
 * 个人从业者模拟数据
 * @type {Array<{id: string, name: string, desc: string}>}
 */
const personList = ref([
  { id: "p1", name: "张三", desc: "UI设计师 5年经验" },
  { id: "p2", name: "李四", desc: "前端开发 3年经验" },
  { id: "p3", name: "王五", desc: "文案策划 4年经验" },
  { id: "p4", name: "赵六", desc: "市场推广 2年经验" },
]);

/**
 * 服务商模拟数据
 * @type {Array<{id: string, name: string, desc: string}>}
 */
const companyList = ref([
  { id: "c1", name: "蓝色科技", desc: "专业软件开发" },
  { id: "c2", name: "创意设计坊", desc: "品牌设计与包装" },
  { id: "c3", name: "推广大师", desc: "全渠道推广" },
  { id: "c4", name: "数据录入中心", desc: "数据处理服务" },
]);

/**
 * 选中的个人从业者ID
 * @type {import('vue').Ref<string[]>}
 */
const selectedPersons = ref<string[]>([]);
/**
 * 选中的服务商ID
 * @type {import('vue').Ref<string[]>}
 */
const selectedCompanies = ref<string[]>([]);

/**
 * 区域选择
 * @type {import('vue').Ref<string>}
 */
const regionLevel = ref("city");
/** 区域信息费映射 */
const regionFeeMap: Record<string, number> = {
  city: 1,
  province: 5,
  nation: 8,
};
/**
 * 区域选项
 * @type {Array<{value: string, label: string, fee: number}>}
 */
const regionOptions: Array<{ value: string; label: string; fee: number }> = [
  { value: "city", label: "市级", fee: 1 },
  { value: "province", label: "省级", fee: 5 },
  { value: "nation", label: "全国", fee: 8 },
];
/**
 * 获取区域文本
 * @param {any} val
 * @returns {string}
 */
function getRegionText(val: any) {
  if (val === "city") return "市级";
  if (val === "province") return "省级";
  if (val === "nation") return "全国";
  return "";
}

// 支付
const handlePayment = async () => {
  console.log("formData==", formData);
  console.log("stages==", stages.value);

  if (!formData.title) {
    Taro.showToast({
      title: "请填写任务标题",
      icon: "none",
    });
    return;
  }

  if (!formData.taskType) {
    Taro.showToast({
      title: "请选择任务分类",
      icon: "none",
    });
    return;
  }

  if (!formData.description) {
    //console.log("提交表单", formData)
    Taro.showToast({
      title: "请填写任务描述",
      icon: "none",
    });
    return;
  }

  const total = parseFloat(totalAmount.value);
  if (total <= 0) {
    Taro.showToast({
      title: "请设置任务金额",
      icon: "none",
    });
    return;
  }
  // 打印选中的服务方
  console.log("选中的个人从业者:", selectedPersons.value);
  console.log("选中的服务商:", selectedCompanies.value);
  // 打印区域选择和信息费
  console.log(
    "区域选择:",
    getRegionText(regionLevel.value),
    "信息费:",
    regionFeeMap[regionLevel.value]
  );

  const submitData = {
    title: formData.title,
    taskStages: stages.value,
    taskType: formData.taskType,
    deadline: formData.deadline,
    describe: formData.description,
    cycle: 1,
    labels: tags.value.join(","),
    // stages: stages.value,
    // longitude: formData.longitude || "-165.9479",
    // latitude: formData.latitude || "28.3201",
    recommend: 0,
    city: "西门市",
    industryId: "4",
    range: "1",
  };

  console.log("submitData==", submitData);
  Taro.showModal({
    title: "确认发布",
    content: `任务标题：${formData.title}\n总金额：¥${totalAmount.value}`,
    success: async (res) => {
      if (res.confirm) {
        // API接口
        const res = await post("/task/save", submitData);
        console.log("==>", res);
        if (res.code == 0) {
          Taro.showToast({
            title: `任务发布成功！总金额：¥${totalAmount.value}，即将跳转到支付页面...`,
            icon: "success",
            duration: 3000,
          });
        }
        /*const submitData = {
          title: formData.title,
          price: formData.
        }*/
      }
    },
  });
};

const showCategoryPicker = ref(false);
const categoryValue = ref<string[]>([]);
const categoryText = ref();

// 地图选择器相关
const showMapPicker = ref(false);
const defaultMapLocation = ref({
  latitude: 39.9042,
  longitude: 116.4074,
  address: "北京市",
});
function onCategoryConfirm(val: any) {
  showCategoryPicker.value = false;
  if (val.selectedValue && val.selectedValue.length > 0) {
    categoryValue.value = [String(val.selectedValue[0])];
    categoryText.value = categoryOptions.value.find(
      (item) => item.value === String(val.selectedValue[0])
    )?.text;
    formData.taskType = String(val.selectedValue[0]);
  }
  console.log(formData.taskType);
}

// 任务类别
getCategoryText();
function getCategoryText() {
  post("/dictionary/taskType").then((res) => {
    categoryOptions.value = res.data.map((item: CategoryItem) => ({
      text: item.columns.name,
      value: item.columns.id.toString(),
    }));
  });

  getTaskType().then((res: any) => {
    console.log("res==", res);
  });
}

// 个人从业者
const getPersonal = async () => {
  const res = await post("/dictionary/merchant")
  console.log('==>',res)
  if(res.code == 0) {
    personList.value = res.data.map((item) => ({
      id: item.columns.id,
      name: item.columns.real_name,
      desc: item.columns.brief_introduction
    }))
  }
}
getPersonal()

const showDatePicker = ref(false);
const dateValue = ref("");
function onDateConfirm(val: any) {
  showDatePicker.value = false;
  // 将格式化的时间存入
  formData.deadline = formatDate(val);
}

// 格式化日期字符串
function formatDate(val: any) {
  if (!val) return "";
  if (typeof val === "string") {
    if (/^\d{4}-\d{2}-\d{2}$/.test(val)) return val;
    if (/^\d{4}\/\d{2}\/\d{2}$/.test(val)) return val.replace(/\//g, "-");
    return val;
  }
  if (val && typeof val === "object" && Array.isArray(val.selectedValue)) {
    return val.selectedValue.join("-");
  }
  return "";
}

const handlePersonCheck = (val: boolean, id: string) => {
  const idx = selectedPersons.value.indexOf(id);
  if (val && idx === -1) selectedPersons.value.push(id);
  if (!val && idx !== -1) selectedPersons.value.splice(idx, 1);
};
const handleCompanyCheck = (val: boolean, id: string) => {
  const idx = selectedCompanies.value.indexOf(id);
  if (val && idx === -1) selectedCompanies.value.push(id);
  if (!val && idx !== -1) selectedCompanies.value.splice(idx, 1);
};

/**
 * 处理位置确认
 */
const handleLocationConfirm = (location: any) => {
  formData.location = location.address;
  // 更新提交数据中的经纬度
  formData.longitude = location.longitude;
  formData.latitude = location.latitude;

  Taro.showToast({
    title: "位置选择成功",
    icon: "success",
  });
};

defineExpose({ handlePersonCheck, handleCompanyCheck });
</script>

<style lang="scss">
.bgs {
  .nut-cell-group__wrap {
    box-shadow: none !important;
  }
  .nut-checkbox {
    margin-right: 0 !important;
  }
  .nut-radio {
    margin-right: 0 !important;
    margin-bottom: 0 !important;
  }
}
</style>
